package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.enums.RecruitStatusEnum;
import com.xmy.cultivate.mapper.GradeCustomSetMapper;
import com.xmy.cultivate.mapper.RecordCourseMapper;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 * 班级自定义设置 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2025-03-29
 */
@Service
public class GradeCustomSetServiceImpl extends ServiceImpl<GradeCustomSetMapper, GradeCustomSet> implements IGradeCustomSetService {


    @Autowired
    IGradeCustomGradeService iGradeCustomGradeService;


    @Autowired
    private RecordCourseMapper recordCourseMapper;

    @Autowired
    IGradeService iGradeService;

    @Autowired
    ICourseService iCourseService;

    @Autowired
    IClassRoomService iClassRoomService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    IDictService iDictService;

    @Autowired
    ICourseSchedulingAlwaysService iCourseSchedulingAlwaysService;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    ISubjectsService iSubjectsService;

    @Autowired
    IdWorker idWorker;

    @Autowired
    ICourseSchedulingService iCourseSchedulingService;

    @Override
    @Transactional
    public void gradeCustomCreate(Long gradeCustomSetId,Long createdId) throws ParseException {
        GradeCustomSet gradeCustomSet = this.getById(gradeCustomSetId);
        Long schoolId = gradeCustomSet.getSchoolId();
        Integer lessonType = gradeCustomSet.getLessonType();
        Integer yearPart = gradeCustomSet.getYearPart();
        Integer quarterNum = gradeCustomSet.getQuarterNum();
        Long subjectsId = gradeCustomSet.getSubjectsId();

        QueryWrapper<GradeCustomGrade> gradeCustomGradeQueryWrapper = new QueryWrapper<>();
        gradeCustomGradeQueryWrapper.eq("grade_custom_set_id",gradeCustomSet.getId());
        gradeCustomGradeQueryWrapper.eq("deleted",0);
        List<GradeCustomGrade> gradeCustomGradeList = iGradeCustomGradeService.list(gradeCustomGradeQueryWrapper);

        for (GradeCustomGrade gradeCustomGrade:gradeCustomGradeList){
            this.createGradeAuto(schoolId,lessonType,yearPart,quarterNum,subjectsId, gradeCustomGrade, createdId);
        }
    }

    public void createGradeAuto(Long schoolId,Integer lessonType,Integer yearPart,Integer quarterNum,Long subjectsId, GradeCustomGrade gradeCustomGrade,Long createdId) throws ParseException {

        QueryWrapper<Course> courseQw = new QueryWrapper<>();
        courseQw.eq("status", 1);
        courseQw.eq("deleted", 0);
        courseQw.and(i -> i.eq("opening_school_type", 1).or().inSql("id", "select for_id from appoint_school where type=1 and school_id =" + schoolId));
        courseQw.in("subjects_id", subjectsId);
        courseQw.in("quarter_num", quarterNum);
        courseQw.eq("lesson_type", lessonType);
        courseQw.last( "limit 1");
        Course course = iCourseService.getOne(courseQw);
        if (course != null){
            //教室
            QueryWrapper<ClassRoom> classRoomQueryWrapper =  new QueryWrapper<>();
            classRoomQueryWrapper.eq("deleted",0);
            classRoomQueryWrapper.eq("lesson_type",lessonType);
            classRoomQueryWrapper.and(wrapper->wrapper.in("school_id",schoolId).or().eq("school_id",0));
            classRoomQueryWrapper.orderByDesc("id");
            classRoomQueryWrapper.last("limit 1");
            ClassRoom classRoom = iClassRoomService.getOne(classRoomQueryWrapper);
//            if (classRoom==null){
//                System.out.println(schoolId+"：教室不存在，科目："+subjectsId);
//                continue;
//            }

            //老师
            String status = "1";
            QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();
            staffQueryWrapper.eq("is_teacher", 1);
            staffQueryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
            staffQueryWrapper.and(i -> i.eq("scope_class_mode", 1).or().inSql("id", "select for_id from appoint_school where type=4 and school_id in(" + schoolId + ")"));
            staffQueryWrapper.eq("deleted", 0);
            staffQueryWrapper.last("limit 1");
            Staff staff = iStaffService.getOne(staffQueryWrapper);
//            if (staff==null){
//                System.out.println(schoolId+"：老师不存在，科目："+subjectsId);
//                continue;
//            }

            //是否假期
            Integer isVacation = iDictService.getIsVacation(quarterNum);
            Integer gradeSection = CommonUtil.getGradeSectionForYearClassId(course.getYearClassId().getKey());
            LocalDate openDate = iCourseSchedulingAlwaysService.getStartDate(yearPart, course.getQuarterNum(), gradeSection, null);
            LocalDate endDate = iCourseSchedulingAlwaysService.getEndDate(yearPart, course.getQuarterNum(), gradeSection, null);
                            QueryWrapper<Grade> gradeQueryWrapper = new QueryWrapper<>();
                            gradeQueryWrapper.eq("year_part",yearPart);
                            gradeQueryWrapper.eq("quarter_num",quarterNum);
                            gradeQueryWrapper.eq("school_id",schoolId);
                            gradeQueryWrapper.eq("course_id",course.getCourseTypeId());
            String weekDates;

            if (gradeCustomGrade.getSchedulingType().equals("A类")){

                for (Integer i=1;i<=5;i++){
                    weekDates = i.toString();
                    this.createGrade(lessonType,yearPart,quarterNum,schoolId,course,gradeCustomGrade,openDate,endDate,isVacation,classRoom,staff,subjectsId,weekDates,gradeCustomGrade.getSchedulingType(), createdId);
                }
            } else if (gradeCustomGrade.getSchedulingType().equals("B类")){
                for (Integer i : new Integer[]{0, 6}) {
                    weekDates = i.toString();
                    this.createGrade(lessonType, yearPart, quarterNum, schoolId, course, gradeCustomGrade, openDate, endDate, isVacation, classRoom, staff, subjectsId, weekDates, gradeCustomGrade.getSchedulingType(), createdId);
                }
            } else if( gradeCustomGrade.getSchedulingType().equals("A天")){
                weekDates = "A";
                this.createGrade(lessonType,yearPart,quarterNum,schoolId,course,gradeCustomGrade,openDate,endDate,isVacation,classRoom,staff,subjectsId,weekDates,gradeCustomGrade.getSchedulingType(), createdId);
            } else if( gradeCustomGrade.getSchedulingType().equals("B天")){
                weekDates = "B";
                this.createGrade(lessonType,yearPart,quarterNum,schoolId,course,gradeCustomGrade,openDate,endDate,isVacation,classRoom,staff,subjectsId,weekDates,gradeCustomGrade.getSchedulingType(), createdId);
            }
        }
//        return true;
    }


    public boolean createGrade(Integer lessonType,
                               Integer yearPart,
                               Integer quarterNum,
                               Long schoolId,
                               Course course,
                               GradeCustomGrade gradeCustomGrade,
                               LocalDate openDate,
                               LocalDate endDate,
                               Integer isVacation,
                               ClassRoom classRoom,
                               Staff staff,
                               Long subjectsId,
                               String weekDates,
                               String schedulingType,
                               Long createdId) throws ParseException {

        //判断是否已经存在该班级
        QueryWrapper<Grade> gradeQueryWrapper = new QueryWrapper<>();
        gradeQueryWrapper.eq("year_part",yearPart);
        gradeQueryWrapper.eq("quarter_num",quarterNum);
        gradeQueryWrapper.eq("week_dates",weekDates);
        gradeQueryWrapper.eq("scheduling_type",schedulingType);
        gradeQueryWrapper.eq("lesson_type",course.getLessonType());
        gradeQueryWrapper.eq("school_id",schoolId);
        gradeQueryWrapper.eq("subjects_id",subjectsId);
        gradeQueryWrapper.eq("time_start",gradeCustomGrade.getTimeStart());
        gradeQueryWrapper.eq("add_type", 2);
        gradeQueryWrapper.eq("deleted", 0);
        gradeQueryWrapper.eq("time_end",gradeCustomGrade.getTimeEnd());
        Long count = iGradeService.count(gradeQueryWrapper);
        if (count>0){
            //更新
            UpdateWrapper<Grade> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("year_part",yearPart);
            updateWrapper.eq("quarter_num",quarterNum);
            updateWrapper.eq("week_dates",weekDates);
            updateWrapper.eq("scheduling_type",schedulingType);
            updateWrapper.eq("lesson_type",course.getLessonType());
            updateWrapper.eq("school_id",schoolId);
            updateWrapper.eq("subjects_id",subjectsId);
            updateWrapper.eq("time_start",gradeCustomGrade.getTimeStart());
            updateWrapper.eq("time_end",gradeCustomGrade.getTimeEnd());
            updateWrapper.eq("add_type", 2);
            updateWrapper.eq("deleted", 0);
            updateWrapper.set("full_count",gradeCustomGrade.getFullCount());
            iGradeService.update(updateWrapper);
            return true;
        }

        String weekName = CommonUtil.getWeekForId(Integer.parseInt(weekDates));
        String lessonTypeName = CommonUtil.getGradeName(lessonType);
        // 查询当前周内已有的班级数量
        QueryWrapper<Grade> existingGradesQuery = new QueryWrapper<>();
        existingGradesQuery.eq("year_part", yearPart);
        existingGradesQuery.eq("quarter_num", quarterNum);
        existingGradesQuery.eq("week_dates", weekDates);
        existingGradesQuery.eq("school_id", schoolId);
        existingGradesQuery.eq("subjects_id", subjectsId);
        existingGradesQuery.eq("lesson_type", lessonType);
        existingGradesQuery.eq("scheduling_type", schedulingType);
        existingGradesQuery.eq("add_type", 2);
        existingGradesQuery.eq("deleted", 0);

        Long existingCount = iGradeService.count(existingGradesQuery);
        String gradeName = lessonTypeName + "（" + (existingCount + 1) + "）班";

        Grade grade = new Grade();
        grade.setId(idWorker.nextId());
        grade.setYearPart(yearPart);
        grade.setQuarterNum(quarterNum);
        grade.setSchoolId(schoolId);
        grade.setCourseId(course.getId());
        grade.setCourseTypeId(1575859909042028546L);
        grade.setYearClassId(course.getYearClassId());
        grade.setLessonType(lessonType);
        grade.setName(weekName+ gradeName); //班级名称
        grade.setAddType(2); //2自动添加
        grade.setRecruitStatus(RecruitStatusEnum.OPEN);
        grade.setOpenDate(openDate);
        grade.setEndDate(endDate);
        grade.setTimeStart(gradeCustomGrade.getTimeStart());//开始时间
        grade.setTimeEnd(gradeCustomGrade.getTimeEnd());//结束时间
        grade.setIsVacation(isVacation);
        grade.setWeekDates(weekDates);//周几
        grade.setIsAutoScheduling(0);
        grade.setSchedulingType(schedulingType);//类型
        grade.setClassRoomId(classRoom.getId());
        grade.setTeacherId(staff.getId());
        grade.setTeacherName(staff.getName());
        grade.setSubjectsId(subjectsId);
        grade.setIsScheduling(0);
        grade.setFullCount(gradeCustomGrade.getFullCount());
        grade.setStuDeductHour(0);
        grade.setTeaGainHour(0);
        grade.setCreatedId(createdId);
        grade.setIsMakeup(0);
        grade.setIsAutoScheduling(1);

        iGradeService.save(grade);
        iCourseSchedulingService.autoScheduling(grade.getId(),openDate);
        return true;
    }

}
